package utils

import (
	"go-project/dto/requrest"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
)

type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"msg"`
	Data    interface{} `json:"data"`
}
type PaginationResponse struct {
	*Response
	Count      int64               `json:"count"`
	Pagination requrest.Pagination `json:"pagination"`
}

func Error(ctx *gin.Context, code int, message string, httpStatus int) {
	if code == 0 {
		code = ERROR
	}
	if httpStatus == 0 {
		httpStatus = http.StatusOK
	}
	if len(message) == 0 {
		message = GetMsg(ERROR)
	}
	ctx.JSON(httpStatus, Response{
		Code:    code,
		Message: message,
		Data:    nil,
	})
}
func Success(ctx *gin.Context, data interface{}, httpStatus int) {
	if httpStatus == 0 {
		httpStatus = http.StatusOK
	}
	ctx.JSON(httpStatus, Response{
		Code:    SUCCESS,
		Message: GetMsg(SUCCESS),
		Data:    data,
	})
}
func PaginationSuccess(ctx *gin.Context, count int64, data interface{}, pagination requrest.Pagination) {
	response := &Response{
		Code:    SUCCESS,
		Message: GetMsg(SUCCESS),
		Data:    data,
	}
	ctx.JSON(http.StatusOK, PaginationResponse{
		Response:   response,
		Count:      count,
		Pagination: pagination,
	})
}

type Permission struct {
	ID       uint          `json:"value"`
	Name     string        `json:"name"`
	ParentID uint          `json:"parent_id"`
	Children []*Permission `json:"children"`
}

var mu sync.Mutex

func BuildPermissionTree(permissions []*Permission) {
	permissionByID := make(map[uint]*Permission)
	for _, p := range permissions {
		mu.Lock()
		permissionByID[p.ID] = p
		mu.Unlock()
	}
	var wg sync.WaitGroup
	for _, p := range permissions {
		if p.ParentID != 0 {
			wg.Add(1)
			go func(p *Permission) {
				defer wg.Done()
				mu.Lock()
				parent := permissionByID[p.ParentID]
				parent.Children = append(parent.Children, p)
				mu.Unlock()
			}(p)
		}
	}

	wg.Wait()
}
